﻿using UnityEngine;
using System.Collections;
using ProtoBuf.Message;
using System.Collections.Generic;


namespace UI
{

   
    public class AchievementPage : Page
    {
        public UIScrollView scrollView;
        public SimpleGrid grid;
        public GameObject achievementItem;

        private int redcount;
        public List<GameObject> items = new List<GameObject>();

        protected override void DoClose()
        {           
            foreach(var item in grid.childs)
            {
                Destroy(item);
            }
            grid.childs.Clear();
            base.DoClose();
        }
        protected override void DoOpen()
        {
			
            GetComponent<PageTweener>().Play();
            CreateAchievementList();
            base.DoOpen();
        }

        public override void DoReopen()
        {

            base.DoReopen();
        }

        public void CreateAchievementList()
        {
            NetAPI.SendHttp(OpDefine.CSAchievementList, new CSAchievementList(), (obj, ok) =>
                {
                    
                    if (ok)
                    {
                        redcount = 0;
                        SCAchievementList msg = obj.kBody as SCAchievementList;
                        foreach (var iteminfo in msg.list)
                        {
                            GameObject go = Instantiate(achievementItem);
                            go.transform.parent = grid.transform;
                            go.transform.localPosition = Vector3.zero;
                            go.transform.localScale = Vector3.one;
                            go.GetComponent<AchievementItem>().InitItemWithInfo(iteminfo);
                            grid.Reposition();
                            grid.AddChild(go);
                            if (iteminfo.state == 0)
                            {
                                redcount++;
                                StaticData.redTips.SetPointState(RedPointTip.Red.achievement, 1);
                            }

                            var script = go.GetComponent<AchievementItem>();
                            script.m_update_red_point = ChangeRedPointState;
                        }                        
                        scrollView.ResetPosition();
                    }
                });
        }

        public void ChangeRedPointState()
        {
            redcount--;
            if(redcount<= 0)
            {
                StaticData.redTips.SetPointState(RedPointTip.Red.achievement,0);
            }
        }

    }
}